package com.winz.cultureapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.winz.cultureapp.R;
import com.winz.cultureapp.base.BaseAppCompatActivity;
import com.winz.cultureapp.constants.Constants;
import com.winz.cultureapp.entity.ActivityDesBean;
import com.winz.cultureapp.entity.BookFixBean;
import com.winz.cultureapp.entity.UserInfoBean;
import com.winz.cultureapp.entity.request.ActivityBookReq;
import com.winz.cultureapp.http.OnResponeListener;
import com.winz.cultureapp.http.request.UserCollectionReq;
import com.winz.cultureapp.http.util.HttpUitls;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;
import com.winz.cultureapp.utils.SharePrefsUtil;
import com.winz.cultureapp.widge.ShareSomething;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 活动 -- 活动详情
 */
public class ActvitiyDesActivity extends BaseAppCompatActivity {

    @BindView(R.id.wv_content)
    WebView mWv_content;
    @BindView(R.id.tv_top_title)
    TextView mTv_top_title;
    @BindView(R.id.iv_right)
    ImageView mIv_right;
    @BindView(R.id.progress)
    ProgressBar mProgress;
    @BindView(R.id.iv_love)
    ImageView mIv_love;

    @BindView(R.id.tv_join)
    TextView mTv_join;
    private String href;
    private String activityId;
    private ActivityDesBean.DataBean mData;


    @Override
    protected int contentView() {
        return R.layout.activity_activity_des;
    }

    @Override
    protected void initViews() {
        mIv_right.setVisibility(View.VISIBLE);
        mIv_right.setImageResource(R.drawable.icon_share);
        mTv_top_title.setText("活动详情");

        mWv_content.getSettings().setJavaScriptEnabled(true);//设置WebView支持JS
        mWv_content.getSettings().setDefaultTextEncodingName("utf-8");//设置解码时的字符集
        mWv_content.getSettings().setLoadWithOverviewMode(true);
        mWv_content.getSettings().setUseWideViewPort(true);
        mWv_content.getSettings().setSupportZoom(true);
        mWv_content.getSettings().setBuiltInZoomControls(true);
        mWv_content.getSettings().setDomStorageEnabled(true);
        mWv_content.getSettings().setBuiltInZoomControls(false);
        mWv_content.setWebViewClient(new WebViewClient() {
            /*
            此处能拦截超链接的url,即拦截href请求的内容.
            */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                mWv_content.loadUrl(url);

                return true;
            }

        });
        mWv_content.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    mProgress.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    mProgress.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    mProgress.setProgress(newProgress);//设置进度值

                }
            }
        });


    }

    @Override
    protected void loadDatas(Intent intent) {
        if (intent != null) {
            if (intent.getExtras() != null) {
                href = intent.getExtras().getString(Constants.KEY.ACTIVITY.ITEM_DES_HREF);
                activityId = intent.getExtras().getString(Constants.KEY.ACTIVITY.ITEM_ID);

                if (TextUtils.isEmpty(activityId)) {
                    showMsg("活动不存在");
                } else {
                    getDes();
                }

                mWv_content.loadUrl(href);


            }
        }
    }

    private void getDes() {
        HttpUitls.onGetByToken("activity_detail", SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN), activityId, new OnResponeListener<ActivityDesBean>() {
            @Override
            public void onSuccess(ActivityDesBean bean) {
                Logger.d("activity_detail==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0) {
                    mData = bean.data;
                    changeCollection();
                    checkActivityStatus();
                } else {
                    showMsg(bean.msg);
                }
            }

            @Override
            public void onFailed(String error) {
                Logger.d("activity_detail==>>", error);

            }
        });
    }

    /*
        收藏状态显示
     */
    private void changeCollection() {
        if (mData.collectionStatus == 1) {
            mIv_love.setImageResource(R.drawable.icon_love_sel);
        } else {
            mIv_love.setImageResource(R.drawable.icon_love_nor);
        }
    }


    private void checkActivityStatus() {
        switch (mData.activityStatus) {
            case 0: // 未开始
                mTv_join.setBackgroundColor(getResources().getColor(R.color.base_color));
                mTv_join.setClickable(true);
                break;
            case 1: // 已开始
                mTv_join.setBackgroundColor(getResources().getColor(R.color.unchecked_color));
                mTv_join.setText("活动已开始");
                mTv_join.setClickable(false);
                break;
            case 2: // 已结束
                mTv_join.setBackgroundColor(getResources().getColor(R.color.unchecked_color));
                mTv_join.setText("活动已结束");
                mTv_join.setClickable(false);
                break;
        }
    }

    @OnClick({R.id.fl_back, R.id.rl_right, R.id.ll_collection, R.id.tv_join})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_back:
                finish();

                break;
            case R.id.rl_right:
                ShareSomething shareSomething = new ShareSomething(this);
                shareSomething.forShare(mData.title,mData.description,Constants.URL.IP + "/activity/detail/" + mData.activityId,mData.imageUrl);
                break;
            case R.id.ll_collection:
                collection();
                break;
            case R.id.tv_join:

                if (mData.unitType == 0) {
                    // 固定场馆
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.KEY.ACTIVITY.ITEM_ID, mData.activityId);
                    bundle.putString(Constants.KEY.ACTIVITY.ITEM_TITLE, mData.title);
                    bundle.putSerializable(Constants.KEY.ACTIVITY.DATA, mData);
                    startActivity(SelSeatActivity.class, false, bundle, 0);
                } else {
                    // 非固定场馆  跳过选座，其他一样
                    join();
                }

                break;
        }
    }

    private void join() {
        String token = SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN);
        HttpUitls.onPostByToken("activity_book",token, new ActivityBookReq(activityId,new ArrayList<>()),new OnResponeListener<BookFixBean>() {
            @Override
            public void onSuccess(BookFixBean bean) {
                HttpUitls.isExpire(bean.code);
                Logger.d("activity_book==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0){
                    if (mData.money == 0){
                        // 不需要支付
                        showMsg("预定成功");
                        setResult(RESULT_OK);
                        Bundle bundle = new Bundle();
                        bundle.putInt("index",1);
                        startActivity(PersonalRecordActivity.class, true,bundle);
                    }else {
                        // 调支付
                        startActivity(ActivityOrderActivity.class,false);
                    }

                }else {
                    showMsg(bean.msg);
                }

                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                Logger.d("activity_book==>>", error);
            }
        });
    }

    /**
     * 添加收藏
     */
    private void collection() {
        showProgressDialog();

        HttpUitls.onPostByToken(mData.collectionStatus == 0 ? "user_collection_save" : "user_collection_cancel", SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN), new UserCollectionReq(mData.activityId, "1"), new OnResponeListener<UserInfoBean>() {
            @Override
            public void onSuccess(UserInfoBean bean) {
                Logger.d(mData.collectionStatus == 0 ? "user_collection_save" : "user_collection_cancel" + "==>>", JsonUtil.getJsonFromObj(bean));
                HttpUitls.isExpire(bean.code);
                if (bean.code == 0) {
                    showMsg(mData.collectionStatus == 0 ? "收藏成功" : "取消收藏");
                    mData.collectionStatus = mData.collectionStatus == 0 ? 1 : 0;
                    changeCollection();
                } else {
                    showMsg(bean.msg);
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                Logger.d("user_collection_save==>>", error);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            finish();
        }
    }

}
